Page({
  data: {
    userInfo:{},
    _id:'',
    editType:'add',
    showDialog:false,
    showDialog1:false,
    newType:'',
    db:null,
    categories: [],
    movingItem: null
  },

  onLoad(options) {
    // 在任何页面/组件中获取
    const app = getApp();
    console.log(app.globalData.env); // 输出: your-env-id
    // 获取默认环境的数据库引用
    this.setData({
      db:app.globalData.db,
      userInfo:wx.getStorageSync('userInfo')
    })
    app.globalData.refreshType = 'true'

    if(options && options.activeId){
      app.globalData.activeId = options.activeId
    }
    this.loadCategories();
  },

  // 加载分类列表
  loadCategories() {
    wx.showLoading({
      title: '加载中...',
    })
    // 获取指定集合的引用
    // const collection = db.collection('type')
    // console.log('collection',__wxConfig.envVersion,collection)
    this.data.db.collection('type').orderBy('order','asc')
    .where({
      _openid:this.data.userInfo._openid
    })
    // .orderBy('createTime', 'desc')
    .get()
    .then(res => {
      console.log('res',res)
      if(res && res.data && res.data.length > 0){
        this.setData({
          categories:res.data,
        })
      }else{
        wx.showToast({ title: '加载分类数据为空', icon: 'none' })
        this.setData({ categories:[]});
      }
      // this.setData({ todos: res.data })
    })
    .catch(err => {
      wx.showToast({ title: '加载分类数据失败', icon: 'none' })
      this.setData({ categories:[]});
    }).finally(() => {
      wx.hideLoading()
    })
  },

  // 跳转到新增页面
  navigateToAdd() {
    wx.navigateTo({ url: '/pages/category/edit' });
  },

  // 编辑分类
  editCategory(e) {
    const id = e.currentTarget.dataset.id;
    const name = e.currentTarget.dataset.name;
    this.setData({
      showDialog:true,
      editType:'edit',
      _id:id,
      newType:name
    })
  },

  // 删除分类
  deleteCategory(e) {
    const id = e.currentTarget.dataset.id;
    this.setData({
      showDialog1:true,
      _id:id,
    })
  },

  // 拖动开始
  onMovableChange(e) {
    if (e.detail.source === 'touch') {
      if (e.detail.state === 'start') {
        this.setData({ movingItem: e.currentTarget.dataset.id });
      } else if (e.detail.state === 'end') {
        const movingId = this.data.movingItem;
        const categories = this.data.categories;
        const movingIndex = categories.findIndex(item => item.id === movingId);
        
        // 计算目标位置
        const targetIndex = this.calculateTargetIndex(movingIndex, e.detail.y);
        
        if (targetIndex !== movingIndex) {
          this.reorderCategories(movingId, categories[targetIndex].id);
        }
        
        this.setData({ movingItem: null });
      }
    }
  },

  // 计算目标位置
  calculateTargetIndex(currentIndex, deltaY) {
    const itemHeight = 140; // 每个分类项的高度
    const maxIndex = this.data.categories.length - 1;
    let targetIndex = currentIndex + Math.round(deltaY / itemHeight);
    
    if (targetIndex < 0) return 0;
    if (targetIndex > maxIndex) return maxIndex;
    return targetIndex;
  },

  // 重新排序
  reorderCategories(draggedId, droppedId) {
    wx.request({
      url: 'https://your-api.com/categories/reorder',
      method: 'PATCH',
      data: { draggedId, droppedId },
      success: () => {
        this.loadCategories();
      },
      fail: () => {
        wx.showToast({ title: '排序失败', icon: 'none' });
      }
    });
  },
  toTopFun(e){
    const index = e.currentTarget.dataset.index;
    const _id = e.currentTarget.dataset.id;
    console.log('index',index)
    if (index > 0) {
      // 交换数组元素
      const arr = JSON.parse(JSON.stringify(this.data.categories))
      const order = arr[index].order
      arr[index].order = arr[index - 1].order
      arr[index -1 ].order = order
      const newArr = [arr[index],arr[index - 1]]
      this.updateTypeFun(newArr)
    }
  },
  toDownFun(e){
    const index = e.currentTarget.dataset.index;
    const _id = e.currentTarget.dataset.id;
    if (index < this.data.categories.length - 1) {
      // 交换数组元素
      const arr = JSON.parse(JSON.stringify(this.data.categories))
      const order = arr[index].order
      arr[index].order = arr[index + 1].order
      arr[index + 1].order = order
      const newArr = [arr[index],arr[index + 1]]
      this.updateTypeFun(newArr)
    }
  },
  async updateTypeFun(arr){

    try{
      // wx.showLoading({
      //   title: '加载中...',
      // })
      for(let key in arr){
        await this.data.db.collection('type').doc(arr[key]._id).update({
          data: {
            order:arr[key].order
          }
        })
      }
      this.loadCategories()

    }catch(err){
      console.log('err',err)
      wx.showToast({ title: '排序失败', icon: 'none' });
      // wx.hideLoading()
    }

  },
  onInputChange(event){
    const value = event.detail
    if (value.length > 6) {
      this.setData({ newType: value.slice(0, 6) }); // 强制截断
      wx.showToast({
        title: '输入长度不能超过6个字',
        icon: 'none'
      })
    } else {
      this.setData({ newType: value });
    }
  },
  onConfirm(){
     // 检查是否只包含数字
     if(this.data.newType === ''){
      wx.showToast({ title: '请输入分类名称', icon: 'none' });
      return;
     }
     if(this.data.editType === 'add'){
       let order= 0
       if(this.data.categories.length > 0){
         order = this.data.categories[this.data.categories.length - 1].order + 1
       }
      this.data.db.collection('type').add({
        data:{
          name:this.data.newType,
          order:order
        },
        success: () => {
          this.onCancel()
         this.loadCategories();
       },
      })
     }else if(this.data.editType === 'edit'){
      this.data.db.collection('type').doc(this.data._id).update({
        data:{
          name:this.data.newType,
        },
        success: () => {
         this.onCancel()
         this.loadCategories();
       },
      })
     }

  },
  onCancel(){
    console.log('onCancel')
    this.setData({ showDialog: false,showDialog1: false,newType:'',_id:'',editType:'add' });
  },
  addTypeFun(){
    this.setData({ showDialog: true ,editType:'add'});
  },
  close(){
    this.setData({
      showDialog1:false
    })
  },
  yesToDel(){
    wx.showLoading({
      title: '删除中...',
    })
    this.data.db.collection('type').doc(this.data._id).remove({
      success: res => {
        wx.hideLoading()
        wx.showToast({
          title: '删除成功',
          icon: 'none'
        })
        this.onCancel()
        this.loadCategories();
      },
      fail: err => {
        wx.hideLoading()
        wx.showToast({
          title: '删除失败',
          icon: 'none'
        })
      }
    })
  },
});